package com.code.zjm.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.widget.TextView;
import android.widget.Toast;

import com.code.zjm.extra.CircleImageView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

/**
 * Created by ZJM on 2017/3/21.
 */

public class ResultActivity extends AppCompatActivity {
    private TextView tvLoginResult;
    private CircleImageView loginImage;
    private static ResultActivity instance;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_result);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        tvLoginResult = (TextView) findViewById(R.id.login_result);
        loginImage = (CircleImageView) findViewById(R.id.login_image);
        instance = this;
        startActivityForResult(new Intent(this, MainActivity.class), 0);
//        checkUserTask("http://172.16.168.188:3001/users/qrcodeRecv?uuid=8");

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            Bundle bundle = data.getExtras();
            String scanResult = bundle.getString("result");
            tvLoginResult.setText("登录成功");
            checkUserTask("http://119.29.88.222:3001/users/qrcodeRecv?uuid=" + scanResult);
//            netWorkTask("http://home.sise.cn/upload/myscseb.png");
        }
    }

    /**
     * 异步检测登录用户，存在就获取用户图片
     *
     * @param url
     */
    public void checkUserTask(String url) {
        new AsyncTask<String, Void, String>() {
            /**
             * 异步执行方法，自动生成一个新的线程
             * @param params
             * @return
             */
            @Override
            protected String doInBackground(String... params) {
                // TODO Auto-generated method stub
                StringBuilder netStr = new StringBuilder();
                try {
                    URL myFileUrl = new URL(params[0]);
                    HttpURLConnection connection = (HttpURLConnection) myFileUrl.openConnection();
                    connection.setDoInput(true); //确认使用 URL 连接进行输入
                    connection.connect();
                    //用 BufferedReader 封装输入流
                    BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line;
                    //将页面Json数据放入StringBuilder中
                    while ((line = br.readLine()) != null) {
                        netStr.append(line);
                    }
                    br.close();//关闭输入流

                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return netStr.toString();
            }

            /**
             * 耗时操作后回调，用于更新UI等主线程操作。
             * @param jsonCont
             */
            @Override
            protected void onPostExecute(String jsonCont) {
                // TODO Auto-generated method stub
                super.onPostExecute(jsonCont);
                try {
                    ArrayList<HashMap<String, Object>> list = parseJson(jsonCont);
                    //循环输出存放了界面json的数据
                    for (int i = 0; i < list.size(); i++) {
                        HashMap<String, Object> map = list.get(i);
                        int code = (int) map.get("code");
                        if (code == 200) {
                            //若用户扫码成功，异步获取用户图片
                            getPicTask("http://172.16.168.188:3001" + map.get("face"));
                        } else if (code == 602) {
                            //用户扫码失败，输出json提示信息
                            tvLoginResult.setText(map.get("message").toString());
                            loginImage.setImageResource(R.drawable.mz2);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }.execute(url);
    }

    /**
     * 异步获取图片后更新 UI
     *
     * @param url 图片 URL
     */
    public void getPicTask(String url) {

        new AsyncTask<String, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(String... params) {
                // TODO Auto-generated method stub
                Bitmap bitmap = null;
                try {
                    URL myFileUrl = new URL(params[0]);
                    HttpURLConnection connection = (HttpURLConnection) myFileUrl.openConnection();
                    connection.setDoInput(true);//确认使用 URL 连接进行输入
                    connection.connect(); //连接
                    InputStream is = connection.getInputStream();//获取界面输入流
                    bitmap = BitmapFactory.decodeStream(is);//将输入流转化为Bitmap
                    is.close();//关闭流
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                return bitmap;
            }

            @Override
            protected void onPostExecute(Bitmap bitmap) {
                // TODO Auto-generated method stub
                super.onPostExecute(bitmap);
//                Toast.makeText(ResultActivity.this, result.toString(), Toast.LENGTH_SHORT).show();
                if (bitmap == null) {
                    Toast.makeText(ResultActivity.this, "图片加载失败", Toast.LENGTH_SHORT).show();
//                    tvLoginResult.setText("登录失败");
                    return;
                }
                loginImage.setImageBitmap(bitmap);
            }
        }.execute(url);
    }

    /**
     * 解析页面json
     *
     * @param jsonStr
     * @return
     * @throws JSONException
     */
    public ArrayList<HashMap<String, Object>> parseJson(String jsonStr) throws JSONException {
        ArrayList<HashMap<String, Object>> jsonList = new ArrayList<>();//存放json的List
        Object checkStr = new JSONTokener(jsonStr).nextValue(); //用于后续动态判断checkStr的类型

        if (checkStr instanceof JSONArray) {//JSONArray 类型
            JSONArray jsonArr = (JSONArray) checkStr;
            JSONObject faceJson = (JSONObject) jsonArr.get(0);
            JSONObject codeJson = (JSONObject) jsonArr.get(1);
            HashMap<String, Object> map = new HashMap<>();
            map.put("face", faceJson.getString("face"));
            map.put("code", codeJson.getInt("code"));
            jsonList.add(map);
        } else if (checkStr instanceof JSONObject) {//JSONObject 类型
            JSONObject jsonO = (JSONObject) checkStr;
            HashMap<String, Object> map = new HashMap<>();
            Iterator<String> keys = jsonO.keys();
            while (keys.hasNext()) {
                String key = keys.next();
                map.put(key, jsonO.get(key));
            }
            jsonList.add(map);
        }
        return jsonList;
    }


    public static ResultActivity getInstance() {
        return instance;
    }
}
